import React, {Component} from 'react';
import {
  Alert,
  Modal,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Dimensions,
} from 'react-native';
import {Picker} from '@react-native-picker/picker';
import RootSiblings from 'react-native-root-siblings';
import Api from '../../Api';
import {showToast} from '../../utils';

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      selectedValue: '',
      options: [],
    };
  }

  showModal = () => {
    const {pickType} = this.props;
    if (pickType === 'province' && !this.pid) {
      showToast('请先选择国家');
      return;
    }
    if (pickType === 'city' && !this.pid) {
      showToast('请先选择省份');
      return;
    }
    if (pickType === 'county' && !this.pid) {
      showToast('请先选择市');
      return;
    }
    this.mask = new RootSiblings(<View style={styles.maskStyle} />);
    this.getRegion();
    this.setState({
      modalVisible: true,
    });
  };

  hideModal = () => {
    this.setState({
      modalVisible: false,
    });
    if (this.mask instanceof RootSiblings) {
      this.mask.destroy();
    }
  };

  setSetectValue = value => {
    // 记录之前的value
    this.prevSelectedValue = this.state.selectedValue;
    this.setState({
      selectedValue: value,
    });
  };

  getPickerText(pickType) {
    switch (pickType) {
      case 'country':
        return '国家';
      case 'province':
        return '省份';
      case 'city':
        return '市';
      case 'county':
        return '区';
    }
  }

  getRegion() {
    let pid = this.pid || 0;
    Api.getRegion(pid).then(res => {
      // [{"adcode": "86", "gmtCreate": 1602575573000, "gmtModified": 1602582104000, "id": 1, "isDeleted": "0", "level": 0, "name": "中国", "pid": 0}]
      this.setState({
        options: res.content || [],
      });
    });
  }

  handleConfirm = () => {
    const {options, selectedValue} = this.state;
    let name = selectedValue;
    if (!name && options.length) {
      name = options[0].name;
      this.setState({
        selectedValue: name,
      });
    }
    const option = options.find(item => item.name === name);
    if (option) {
      const id = option.id;
      this.props.onChange &&
        this.props.onChange({
          name,
          pickType: this.props.pickType,
          id,
        });
    }
    this.hideModal();
  };

  handleCancel = () => {
    this.setState({
      selectedValue: this.prevSelectedValue || this.props.selectedValue || '',
    });
    this.hideModal();
  };

  clear = () => {
    if (this.state.selectedValue) {
      this.setState({
        selectedValue: '',
      });
    }
  };

  render() {
    const {pickType, prefix = '请选择', extraStyle = {}} = this.props;
    const {modalVisible, selectedValue, options} = this.state;
    return (
      <View style={styles.centeredView}>
        <Modal
          animationType="side"
          transparent={true}
          visible={modalVisible}
          onRequestClose={this.handleCancel}>
          <View style={styles.modalStyle}>
            <View style={styles.modalHeader}>
              <TouchableOpacity
                style={styles.headerBtn}
                onPress={this.handleCancel}>
                <Text style={styles.headerText}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.headerBtn}
                onPress={this.handleConfirm}>
                <Text style={styles.headerText}>确认</Text>
              </TouchableOpacity>
            </View>
            <Picker
              selectedValue={selectedValue}
              onValueChange={(itemValue, itemIndex) =>
                this.setSetectValue(itemValue)
              }>
              {options.map(item => {
                return (
                  <Picker.Item
                    label={item.name}
                    value={item.name}
                    key={item.id}
                  />
                );
              })}
            </Picker>
          </View>
        </Modal>
        <TouchableOpacity
          style={[styles.pickWrap, extraStyle]}
          onPress={this.showModal}>
          <Text
            numberOfLines={1}
            style={[styles.pickItem, selectedValue && styles.pickItemActive]}>
            {selectedValue || `${prefix}${this.getPickerText(pickType)}`}
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  maskStyle: {
    position: 'absolute',
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    width: width,
    height: height,
  },
  modalStyle: {
    position: 'absolute',
    left: 0,
    bottom: 0,
    width: width,
    flex: 1,
    backgroundColor: '#ffffff',
    zIndex: 99,
  },
  modalHeader: {
    height: 50,
    backgroundColor: '#f5f5f5',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  headerBtn: {
    height: 50,
    width: 80,
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerText: {
    fontSize: 18,
    color: '#5196FD',
  },
  pickWrap: {
    width: 90,
    height: 50,
    borderRadius: 2,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
  },
  pickItem: {
    fontSize: 14,
    color: '#b2b2b2',
  },
  pickItemActive: {
    color: '#333',
  },
});

export default App;
